<template>
  <div class="grid">
    <canvas
      ref="canvas"
      class="canvas"
    ></canvas>
    <div
      @mousedown="mousedown"
      @mousemove="mousemove"
      @mouseup="mouseup"
      class="content"
    ></div>
  </div>
</template>

<script lang="ts">
import { ref, Ref, defineComponent, onMounted } from 'vue'

interface LPosition {
  x: number;
  y: number;
}

export default defineComponent({
  name: 'shuiguo',
  setup () {
    const height = 200
    const width = 200
    const canvas = ref<HTMLCanvasElement | null>(null)
    let canvasDom: HTMLCanvasElement | null = null
    let ctx: CanvasRenderingContext2D | null = null
    let mousedownFlag = false

    function mousedown (e: MouseEvent) {
      console.info(e.offsetX, e.offsetY)
      if (ctx) {
        ctx.moveTo(e.offsetX, e.offsetY)
        mousedownFlag = true
      }
    }
    function mouseup () {
      if (canvasDom) {
        canvasDom.height = height
      }
      mousedownFlag = false
    }

    const mousemove = function (e: MouseEvent) {
      if (mousedownFlag && ctx) {
        console.info(e.offsetX, e.offsetY)
        ctx.globalAlpha = 1
        ctx.lineWidth = 2
        ctx.lineTo(e.offsetX, e.offsetY)
        ctx.stroke()
      }
    }
    onMounted(() => {
      console.info(canvas.value)
      canvasDom = (canvas as Ref<HTMLCanvasElement>).value
      canvasDom.height = height
      canvasDom.width = width
      ctx = canvasDom.getContext('2d') as CanvasRenderingContext2D
      // ctx.moveTo(0, 0)
      // ctx.lineTo(200, 100)
      // ctx.stroke()
    })
    return {
      canvas,
      mouseup,
      mousemove,
      mousedown
    }
  }
})

</script>

<style scoped lang="less">
.grid {
  width: 200px;
  height: 200px;
  position: relative;
  border: 1px solid #e0e0e0;
}
.content{
  position: relative;
  z-index: 2;
  width: 100%;
  height: 100%;
  background: #fff;
}
.canvas {
  z-index: 5;
  top:0;
  left: 0;
  position: absolute;
  width: 100%;
  height: 100%;
  pointer-events: none;
}
</style>
